package com.example.match.mui;

import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;


import com.example.match.R;
import com.example.match.camera.CameraInterface;
import com.example.match.camera.FacePicInterface;
import com.example.match.camera.FragmentCamera;
import com.example.mylibrary.MyApp;
import com.example.mylibrary.config.Config;
import com.example.mylibrary.data.ByteImg;
import com.example.mylibrary.data.DataDao;
import com.example.mylibrary.data.StudentInfo;
import com.example.mylibrary.util.ActivityCollector;
import com.example.mylibrary.util.ImageUtil;
import com.example.mylibrary.util.SysApplication;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cn.com.aratek.facelib.AraFaceAuthLib;
import cn.com.aratek.idcard.IDCard;


public class BlankPageActivity extends AppCompatActivity implements FacePicInterface {
    private static final int MAX_VERIFY_COUNT = 5;
    private FragmentManager manager = getSupportFragmentManager();
    private String cardNum;
    private byte[] snapshotFeature;
    private List<StudentInfo> studentInfoAll;
    private ArrayList<ByteImg> bytes;
    private ByteImg byteImg;
    private List<ByteImg> imgList;
    private String stuCode;
    private byte[] cardData = null;
    private FragmentCamera fragment;
    public static Context mContext;
    private AraFaceAuthLib araFaceAuthLib;
    private ExecutorService cachedThreadPool;
    private MyApp app;
    private Bitmap Sbitmap = null;
    private static final int MSG_FACE_RESULT = 8;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blank_page);
        mContext = this;
        //将activity页面添加到list   进行统一关闭
        SysApplication.getInstance().addActivity(this);

        ActionBar actionBar =  getActionBar();
        if(actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowTitleEnabled(false);
        }
        init();
        faceResult();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:   //返回键的id
                finish();
                break;
        }
        return true;

    }
    private void init() {
        araFaceAuthLib = MainUIActivity.getAraFaceAuthLib();
        cachedThreadPool = Executors.newCachedThreadPool();
        app = MyApp.getInstance();

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        startActivity(new Intent(this,MainUIActivity.class));
        ActivityCollector.removeActivity(this);
        finish();
    }

    public FragmentCamera getFragment() {
        return fragment;
    }

    private void faceResult(){
        bytes=new ArrayList<>();
        byteImg = new ByteImg();
        imgList = new ArrayList<>();
        imgList = DataDao.imgAll();
        for (int i = 0; i< imgList.size(); i++){
            ByteImg byteImg=new ByteImg();
            byteImg = imgList.get(i);
            if(byteImg.getByteImg() !=null){
                cardData = byteImg.getByteImg();
                byteImg.setByteImg(cardData);
                byteImg.setImgId(imgList.get(i).getImgId());
                bytes.add(byteImg);
            }
        }

        fragment = new FragmentCamera();
        fragment.setBytes(bytes);

        CameraInterface.setVerifyCount(MAX_VERIFY_COUNT);
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.face_content, fragment);
        transaction.addToBackStack(null);
        transaction.commit();

    }
    @Override
    public void fromPic(int requestCode, int resultCode, Intent data) {

        if (requestCode == 222){
            if (resultCode ==1){
                float score = data.getFloatExtra("score",0);
                snapshotFeature = data.getByteArrayExtra("snapshotFeature");
                stuCode = data.getStringExtra("stuCode");
                saveData( snapshotFeature,score, stuCode);
            }else {

            }
        }
    }

    private void saveData(final byte[] snapshotFeature, final float score, final String stuCode) {

        cachedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                setSnapshotFeature(snapshotFeature,score,stuCode);
            }


        });

    }

    private void setSnapshotFeature(byte[] snapshotFeature, float score,String stuCode) {
        final Bitmap b = ImageUtil.getRotateBitmap(BitmapFactory.decodeByteArray(snapshotFeature,0,snapshotFeature.length), Config.displayOrientation);
        Sbitmap = b;
        String res = String.valueOf(score);
        mHandler.sendMessage(mHandler.obtainMessage(MSG_FACE_RESULT, res));
        BlankPageActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {

            }
        });

    }


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {

                case  MSG_FACE_RESULT:{
                    String res = (String) msg.obj;
                    float score = Float.valueOf(res);
                    if(score == -1){
                        Toast.makeText(BlankPageActivity.this, "比对失败", Toast.LENGTH_SHORT).show();
                    }else if(score == 0){
                        Toast.makeText(BlankPageActivity.this, "比对失败", Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(BlankPageActivity.this, "比对成功", Toast.LENGTH_SHORT).show();
                        Intent faceIntent = new Intent(BlankPageActivity.this,InfoDisplayActivity.class);
                        //将身份证号传递出去
                        //不能传BItmap对象  只能转成字节进行传递 否则跳转不成功
                        faceIntent.putExtra("snapshotFeature",snapshotFeature);
                        faceIntent.putExtra("stuCode",stuCode);
                        startActivity(faceIntent);

                    }
                    break;
                }


            }


        }

    };


}
